/**
 * 日志上传器 - 定期上传客户端日志到服务器
 * 🔥 使用 JSON 文件缓存，每 12 秒自动上传到服务器
 */
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const { app } = require('electron');
const config = require('./config');
const logger = require('./logger');

class LogUploader {
  constructor() {
    this.logs = [];
    this.uploadInterval = 60 * 1000; // 🔥 优化：60秒上传一次，减少CPU占用
    this.maxLogsPerBatch = 100; // 每批最多上传100条
    this.maxCacheSize = 500; // 🔥 JSON 缓存最多保存 500 条
    this.timer = null;
    this.isUploading = false;
    this.saveTimer = null; // 🔥 文件保存定时器
    this.pendingSave = false; // 🔥 是否有待保存的日志
    
    // 🔥 JSON 缓存文件路径
    this.cacheDir = path.join(app.getPath('userData'), 'logs');
    this.cacheFile = path.join(this.cacheDir, 'log_cache.json');
    
    // 确保缓存目录存在
    if (!fs.existsSync(this.cacheDir)) {
      fs.mkdirSync(this.cacheDir, { recursive: true });
    }
    
    // 🔥 加载缓存的日志
    this.loadCachedLogs();
  }

  /**
   * 🔥 加载缓存的日志
   */
  loadCachedLogs() {
    try {
      if (fs.existsSync(this.cacheFile)) {
        const data = fs.readFileSync(this.cacheFile, 'utf-8');
        const cached = JSON.parse(data);
        if (Array.isArray(cached) && cached.length > 0) {
          this.logs = cached;
          console.log(`📚 从缓存加载 ${this.logs.length} 条日志`);
        }
      }
    } catch (error) {
      console.error('加载日志缓存失败:', error);
      this.logs = [];
    }
  }

  /**
   * 🔥 保存日志到 JSON 缓存
   */
  saveCachedLogs() {
    try {
      // 🔥 防御性检查
      if (!this.logs || !Array.isArray(this.logs)) {
        this.logs = [];
      }
      // 只保存最新的 maxCacheSize 条日志
      const logsToSave = this.logs.slice(-this.maxCacheSize);
      fs.writeFileSync(this.cacheFile, JSON.stringify(logsToSave, null, 2), 'utf-8');
    } catch (error) {
      console.error('保存日志缓存失败:', error);
    }
  }

  /**
   * 添加日志
   */
  addLog(level, message, stack = null) {
    // 🔥 防御性检查
    if (!this.logs || !Array.isArray(this.logs)) {
      this.logs = [];
    }
    
    this.logs.push({
      level,
      message,
      stack,
      timestamp: new Date().toISOString()
    });

    // 🔥 优化：延迟保存，减少文件写入频率
    this.scheduleSave();

    // 如果累积了太多日志，立即上传
    if (this.logs.length >= this.maxLogsPerBatch) {
      this.uploadLogs();
    }
  }

  /**
   * 🔥 计划保存（防抖动）
   */
  scheduleSave() {
    if (this.pendingSave) {
      return;
    }
    
    this.pendingSave = true;
    
    // 🔥 5秒后保存，避免频繁写文件
    if (this.saveTimer) {
      clearTimeout(this.saveTimer);
    }
    
    this.saveTimer = setTimeout(() => {
      this.saveCachedLogs();
      this.pendingSave = false;
    }, 5000);
  }

  /**
   * 启动定期上传
   */
  start() {
    if (this.timer) {
      return;
    }

    console.log(`📤 日志上传器已启动 - 每 ${this.uploadInterval / 1000} 秒自动上传`);

    // 立即上传一次缓存的日志
    setTimeout(() => this.uploadLogs(), 5000); // 5秒后第一次上传

    // 🔥 设置定时器
    this.timer = setInterval(() => {
      this.uploadLogs();
    }, this.uploadInterval);
  }

  /**
   * 停止上传
   */
  stop() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
    
    // 🔥 清理保存定时器
    if (this.saveTimer) {
      clearTimeout(this.saveTimer);
      this.saveTimer = null;
    }

    // 🔥 停止前保存并上传剩余日志
    this.saveCachedLogs();
    this.uploadLogs();
    console.log('📤 日志上传器已停止');
  }

  /**
   * 上传日志到服务器
   */
  async uploadLogs() {
    // 🔥 防御性检查
    if (!this.logs || !Array.isArray(this.logs)) {
      this.logs = [];
    }
    
    if (this.isUploading || this.logs.length === 0) {
      return;
    }

    this.isUploading = true;

    try {
      const userConfig = config.getUserConfig();
      const serverUrl = config.getServerUrl();

      if (!userConfig.token) {
        console.log('未登录，跳过日志上传');
        this.isUploading = false;
        return;
      }

      // 🔥 获取所有日志（不筛选）
      const logsToUpload = [...this.logs]; // 复制所有日志
      
      if (logsToUpload.length === 0) {
        this.isUploading = false;
        return;
      }

      // 🔥 获取客户端ID
      const clientId = config.getClientId();

      console.log(`📤 上传 ${logsToUpload.length} 条日志到服务器，客户端ID: ${clientId}`);

      // 🔥 上传到服务器（带客户端ID）
      const response = await axios.post(
        `${serverUrl}/api/logs/client/upload`,
        { 
          logs: logsToUpload,
          clientId: clientId  // 🔥 带上客户端ID
        },
        {
          headers: {
            'Authorization': `Bearer ${userConfig.token}`,
            'Content-Type': 'application/json'
          },
          timeout: 30000
        }
      );

      if (response.data.success) {
        console.log(`✅ 日志上传成功: ${logsToUpload.length} 条`);
        // 🔥 上传成功后清空日志
        this.logs = [];
        this.saveCachedLogs();
      } else {
        console.error('日志上传失败:', response.data.message);
        // 失败的日志放回队列
        this.logs.unshift(...logsToUpload);
        // 🔥 保存失败的日志到缓存
        this.saveCachedLogs();
      }
    } catch (error) {
      console.error('上传日志时发生错误:', error.message);
      // 错误时不放回队列，避免一直重试失败的日志
      // 但保存当前缓存
      this.saveCachedLogs();
    } finally {
      this.isUploading = false;
    }
  }

  /**
   * 从日志文件读取最近的日志并上传
   */
  async uploadRecentLogs() {
    try {
      // 获取日志文件路径
      const logDir = path.join(app.getPath('userData'), 'logs');
      const logFilePath = path.join(logDir, 'main.log');
      
      if (!fs.existsSync(logFilePath)) {
        return;
      }

      const logContent = fs.readFileSync(logFilePath, 'utf-8');
      const lines = logContent.split('\n').filter(line => line.trim());
      
      // 只取最近100条
      const recentLines = lines.slice(-100);
      
      const logs = recentLines.map(line => {
        try {
          const parsed = JSON.parse(line);
          return {
            level: parsed.level || 'info',
            message: parsed.message || line,
            stack: parsed.stack || null,
            timestamp: parsed.timestamp || new Date().toISOString()
          };
        } catch (e) {
          return {
            level: 'info',
            message: line,
            stack: null,
            timestamp: new Date().toISOString()
          };
        }
      });

      if (logs.length > 0) {
        this.logs.push(...logs);
        await this.uploadLogs();
      }
    } catch (error) {
      console.error('读取日志文件失败:', error);
    }
  }
}

// 创建单例
const logUploader = new LogUploader();

module.exports = logUploader;
